package com.excellent.CourseUtils;

import okhttp3.*;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

/**
 * 需要添加依赖
 * &lt;!-- https://mvnrepository.com/artifact/com.squareup.okhttp3/okhttp --&gt;
 * &lt;dependency&gt;
 * &lt;groupId&gt;com.squareup.okhttp3&lt;/groupId&gt;
 * &lt;artifactId&gt;okhttp&lt;/artifactId&gt;
 * &lt;version&gt;4.12.0&lt;/version&gt;
 * &lt;/dependency&gt;
 */

class ChatInit {

    static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();

    public static String getConversationId(String appId) {
        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, String.format("{\"app_id\":\"%s\"}", appId));
        Request request = new Request.Builder()
                .url("https://qianfan.baidubce.com/v2/app/conversation")
                .method("POST", body)
                .addHeader("Content-Type", "application/json")
                .addHeader("X-Appbuilder-Authorization", "Bearer bce-v3/ALTAK-jnYex1wotKizobcUiYg8Z/ab021ae321c579d5ea3335f2eac029995a23de3e")
                .build();

        try (Response response = HTTP_CLIENT.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException("Unexpected code " + response);
            }
            String responseBody = response.body().string(); // 只获取一次响应体
            JSONObject jsonObject = new JSONObject(responseBody);
            return jsonObject.getString("conversation_id");
        } catch (IOException e) {
            System.err.println("请求失败: " + e.getMessage());
            return null; // 或者抛出异常
        } catch (JSONException e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) {
        String conversationId = getConversationId("4511bdcb-f453-4e76-9882-c28108fb225b");
        if (conversationId != null) {
            System.out.println(conversationId);
        }
    }
}
